/*
 * @lc app=leetcode.cn id=54 lang=cpp
 *
 * [54] 螺旋矩阵
 */
#include "include.h"
// @lc code=start
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int m = matrix.size();
        int n = matrix[0].size();
        vector<int> res;

        int direction = 0;
        int row = 0;
        int col = -1;
        bool turnOnce = false;
        while (1){
            row += directions_[direction][0];
            col += directions_[direction][1];

            bool outside = row<0 or row>=m or col<0 or col>=n;
            if (outside){
                if (turnOnce){break;}
                
                row -= directions_[direction][0];
                col -= directions_[direction][1];
                direction = (direction + 1) % 4;
                turnOnce = true;
                continue;
            }
            bool visited = matrix[row][col] < -100;
            if (visited){
                if (turnOnce){break;}
                
                row -= directions_[direction][0];
                col -= directions_[direction][1];
                direction = (direction + 1) % 4;
                turnOnce = true;
                continue;
            }

            turnOnce = false;
            res.emplace_back(matrix[row][col]);
            matrix[row][col] = -101;
        }
        return res;
    }
private:
    const int directions_[4][2] = {
            // row, col
            {0, 1},
            {1, 0},
            {0, -1},
            {-1, 0}
        };
};
// @lc code=end

int main(){
    vector<vector<int>> matrix = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    Solution test;
    test.spiralOrder(matrix);
}